<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;

/* handle field output */
function wppb_upload_handler( $output, $form_location, $field, $user_id, $field_check_errors, $request_data ){
    if ( $field['field'] == 'Upload' ){

        /* media upload add here, this should be added just once even if called multiple times */
        wp_enqueue_media();
        /* propper way to dequeue. add to functions file in theme or custom plugin
         function wppb_dequeue_script() {
            wp_script_is( 'wppb-upload-script', 'enqueued' ); //true
            wp_dequeue_script( 'wppb-upload-script' );
        }
        add_action( 'get_footer', 'wppb_dequeue_script' );
         */
        $upload_script_vars = array(
            'nonce'            => wp_create_nonce( 'wppb_ajax_simple_upload' ),
            'ajaxUrl'          => admin_url( 'admin-ajax.php' ),
            'remove_link_text' => __( 'Remove', 'profile-builder' )
        );
        wp_enqueue_script( 'wppb-upload-script', WPPB_PAID_PLUGIN_URL.'front-end/extra-fields/upload/upload.js', array('jquery'), PROFILE_BUILDER_VERSION, true );
        wp_localize_script( 'wppb-upload-script', 'wppb_upload_script_vars', $upload_script_vars );

        $wppb_generalSettings = get_option( 'wppb_general_settings' );

        if ( ( isset( $wppb_generalSettings['extraFieldsLayout'] ) && ( $wppb_generalSettings['extraFieldsLayout'] == 'default' ) ) )
            wp_enqueue_style( 'profile-builder-upload-css', WPPB_PAID_PLUGIN_URL.'front-end/extra-fields/upload/upload.css', false, PROFILE_BUILDER_VERSION );

        $item_title = apply_filters( 'wppb_'.$form_location.'_upload_custom_field_'.$field['id'].'_item_title', wppb_icl_t( 'plugin profile-builder-pro', 'custom_field_'.$field['id'].'_title_translation', $field['field-title'], true ) );
        $item_description = wppb_icl_t( 'plugin profile-builder-pro', 'custom_field_'.$field['id'].'_description_translation', $field['description'], true );

        if( $form_location != 'register' ) {
            if( empty( $request_data[wppb_handle_meta_name( $field['meta-name'] )] ) )
                $input_value = ( (wppb_user_meta_exists($user_id, $field['meta-name']) != null) ? get_user_meta($user_id, $field['meta-name'], true) : '');
            else
                $input_value = $request_data[wppb_handle_meta_name( $field['meta-name'] )];

            if( !empty( $input_value ) && !is_numeric( $input_value ) && apply_filters( 'wppb_upload_field_transform_file_to_attachment', true, $field ) ){
                /* we have a file url and we need to change it into an attachment */
                // Check the type of file. We'll use this as the 'post_mime_type'.
                $wp_upload_dir = wp_upload_dir();
                $file_path = str_replace( $wp_upload_dir['baseurl'], $wp_upload_dir["basedir"], $input_value );
                //on windows os we might have \ instead of / so change them
                $file_path = str_replace( "\\", "/", $file_path );
                $file_type = wp_check_filetype( basename( $input_value ), null );
                $attachment = array(
                    'guid' => $input_value,
                    'post_mime_type' => $file_type['type'],
                    'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $input_value ) ),
                    'post_content'   => '',
                    'post_status'    => 'inherit'
                );

                // Insert the attachment.
                $input_value = wp_insert_attachment( $attachment, $input_value, 0 );
                if( !empty( $input_value ) ) {
                    // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
                    require_once(ABSPATH . 'wp-admin/includes/image.php');
                    // Generate the metadata for the attachment, and update the database record.
                    $attach_data = wp_generate_attachment_metadata($input_value, $file_path);
                    wp_update_attachment_metadata($input_value, $attach_data);
                    /* save the new attachment instead of the url */
                    update_user_meta( $user_id, $field['meta-name'], $input_value );
                }
            }
        }
        else
            $input_value = !empty( $_POST[$field['meta-name']] ) ? sanitize_text_field( $_POST[$field['meta-name']] ) : '';

        if ( $form_location != 'back_end' ){
            $error_mark = ( ( $field['required'] == 'Yes' ) ? '<span class="wppb-required" title="'.wppb_required_field_error($field["field-title"]).'">*</span>' : '' );

            if ( array_key_exists( $field['id'], $field_check_errors ) )
                $error_mark = '<img src="'.WPPB_PLUGIN_URL.'assets/images/pencil_delete.png" title="'.wppb_required_field_error($field["field-title"]).'"/>';

            $extra_attr = apply_filters( 'wppb_extra_attribute', '', $field, $form_location );

			$output = '<label for="'.$field['meta-name'].'">'.$item_title.$error_mark.'</label>';
            $output .= wppb_make_upload_button( $field, $input_value, $extra_attr );
            if( !empty( $item_description ) )
                $output .= '<span class="wppb-description-delimiter">'.$item_description.'</span>';
        }else{
            $item_title = ( ( $field['required'] == 'Yes' ) ? $item_title .' <span class="description">('. __( 'required', 'profile-builder' ) .')</span>' : $item_title );
            $output = '
				<table class="form-table">
					<tr>
						<th><label for="'.$field['meta-name'].'">'.$item_title.'</label></th>
						<td>';
            $output .= wppb_make_upload_button( $field, $input_value );
            $output .='<br/><span class="wppb-description-delimiter">'.$item_description;
            $output .= '
						</td>
					</tr>
				</table>';
        }
        return apply_filters( 'wppb_'.$form_location.'_upload_custom_field_'.$field['id'], $output, $form_location, $field, $user_id, $field_check_errors, $request_data, $input_value );
    }
}
add_filter( 'wppb_output_form_field_upload', 'wppb_upload_handler', 10, 6 );
add_filter( 'wppb_admin_output_form_field_upload', 'wppb_upload_handler', 10, 6 );

/* verifies if an attachment either doesn't exist or already belongs to the user */
function wppb_verify_attachment_id( $attachment_id, $user_id = null ) {
    if ( $attachment_id !== '' && is_numeric( $attachment_id ) ) {
        $attachment = get_post( absint( trim($attachment_id) ) );
        if ( $attachment && $attachment->post_type === 'attachment' ) {
            if ( $user_id ) {
                // Only update if the attachment belongs to the user or has no author (post_author = 0)
                if ( $attachment->post_author == $user_id || $attachment->post_author == 0 ) {
                    return true;
                }
            } else {
                // If no user ID is provided, just check if the attachment has no author
                if ( $attachment->post_author == 0 ) {
                    return true;
                }
            }
        }
    }
    return false;
}

/* updates the field and the author for the attachment  */
function wppb_save_attachment_id( $attachment_id, $field, $user_id ) {
    // Verify that the attachment either doesn't exist or already belongs to the user
    if ( wppb_verify_attachment_id( $attachment_id, $user_id ) ) {
        update_user_meta( $user_id, $field[ 'meta-name' ], absint( $attachment_id ) );
        wp_update_post( array(
            'ID'            => absint( trim( $attachment_id ) ),
            'post_author'   => $user_id
        ) );
    } else {
        update_user_meta( $user_id, $field[ 'meta-name' ], '' );
    }
}

/* handle field save */
function wppb_save_upload_value( $field, $user_id, $request_data, $form_location ){
    if( $field[ 'field' ] == 'Upload' ){
        if ( isset( $field[ 'simple-upload' ] ) && $field[ 'simple-upload' ] == 'yes' && ( !isset( $field[ 'woocommerce-checkout-field' ] ) || $field[ 'woocommerce-checkout-field' ] !== 'Yes' ) ) {
            //Save data in the case the simple upload field is used
            $field_name = 'simple_upload_' . wppb_handle_meta_name( $field[ 'meta-name' ] );
            if( isset( $_FILES[ $field_name ] ) || ( isset( $request_data[ 'pay_gate' ] ) && in_array( $request_data['pay_gate'], array( 'stripe_connect', 'paypal_connect' ) ) ) ){
                if ( !( wppb_belongs_to_repeater_with_conditional_logic( $field ) && !isset( $request_data[ wppb_handle_meta_name( $field[ 'meta-name' ] ) ] ) ) && !( isset( $field[ 'conditional-logic-enabled' ] ) && $field[ 'conditional-logic-enabled' ] == 'yes' && !isset( $request_data[ wppb_handle_meta_name( $field[ 'meta-name' ] ) ] ) ) ){
                    if ( isset( $_FILES[ $field_name ][ 'size' ] ) && $_FILES[ $field_name ][ 'size' ] == 0 ){
                        if ( isset( $request_data[ wppb_handle_meta_name( $field[ 'meta-name' ] ) ] ) ){
                            update_user_meta( $user_id, $field[ 'meta-name' ], sanitize_text_field( $request_data[ wppb_handle_meta_name( $field[ 'meta-name' ] ) ] ) );
                        }
                    }
                    else{
                        $attachment_id = $request_data[ $field[ 'meta-name' ] ];
                        wppb_save_attachment_id( $attachment_id, $field, $user_id );
                    }
                }
            }
        }
        else{
            //Save data in the case the WordPress upload is used
            if ( isset( $request_data[wppb_handle_meta_name( $field['meta-name'] )] ) ){
                $attachment_id = sanitize_text_field( $request_data[wppb_handle_meta_name( $field['meta-name'] )] );
                wppb_save_attachment_id( $attachment_id, $field, $user_id );
            }
        }

        /**
         * Fires after the user meta-data has been updated
         *
         * @param int    $user_id - the ID of the User
         * @param string $request_data[wppb_handle_meta_name( $field['meta-name'] )] - the Attachment ID (also the Attachment-Post ID)
         * @param string $field['meta-name'] - the Upload Field meta-name
         * @param string $field['simple-upload'] - "yes" if the field is a Simple Upload field, empty otherwise
         *
         */
        if ( isset( $request_data[wppb_handle_meta_name( $field['meta-name'] )] ) )
            do_action( 'wppb_upload_field_after_user_meta_update', $user_id, $request_data[wppb_handle_meta_name( $field['meta-name'] )], $field['meta-name'], $field['simple-upload'] );

    }
}
add_action( 'wppb_save_form_field', 'wppb_save_upload_value', 10, 4 );
add_action( 'wppb_backend_save_form_field', 'wppb_save_upload_value', 10, 4 );

/* save file when ec is enabled */
function wppb_add_upload_for_user_signup( $field_value, $field, $request_data ){

    // Save the uploaded file
    // It will have no author until the user's email is confirmed
    if( $field['field'] == 'Upload' ) {
        if( isset( $field[ 'simple-upload' ] ) && $field[ 'simple-upload' ] === 'yes' && ( !isset( $field[ 'woocommerce-checkout-field' ] ) || $field[ 'woocommerce-checkout-field' ] !== 'Yes' ) ) {
            $field_name = 'simple_upload_' . $field['meta-name'];

            if (isset($_FILES[$field_name]) &&
                isset($_FILES[$field_name]['size']) && $_FILES[$field_name]['size'] !== 0 &&
                !(wppb_belongs_to_repeater_with_conditional_logic($field) && !isset($request_data[wppb_handle_meta_name($field['meta-name'])])) &&
                !(isset($field['conditional-logic-enabled']) && $field['conditional-logic-enabled'] == 'yes' && !isset($request_data[wppb_handle_meta_name($field['meta-name'])])) &&
                wppb_valid_simple_upload($field, $_FILES[$field_name])) { /* phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized */ /* no need here */
                return wppb_save_simple_upload_file($field_name);
            }
        } else {
            $attachment_id = $request_data[wppb_handle_meta_name( $field['meta-name'] )];
            if ( wppb_verify_attachment_id( $attachment_id ) ){
                // If the attachment is valid and has no author, return it
                return absint( trim( $attachment_id ) );
            } else {
                // If security checks fail, return empty to prevent file hijacking
                return '';
            }
        }
    }

    return '';
}
add_filter( 'wppb_add_to_user_signup_form_field_upload', 'wppb_add_upload_for_user_signup', 10, 3 );

/* handle simple upload at the WooCommerce Checkout */
function wppb_ajax_simple_upload(){
    check_ajax_referer( 'wppb_ajax_simple_upload', 'nonce' );
    if ( isset($_POST["name"]) ) {
        echo json_encode( wppb_save_simple_upload_file( sanitize_text_field( $_POST["name"] ) ) );
    }
    wp_die();
}
add_action( 'wp_ajax_nopriv_wppb_ajax_simple_upload', 'wppb_ajax_simple_upload' );
add_action( 'wp_ajax_wppb_ajax_simple_upload', 'wppb_ajax_simple_upload' );

/* handle field validation */
function wppb_check_upload_value( $message, $field, $request_data, $form_location ){
    if( $field['field'] == 'Upload' ){
        if( $field['required'] == 'Yes' ){
            if ( isset( $field[ 'simple-upload' ] ) && $field[ 'simple-upload' ] == 'yes' && ( !isset( $field[ 'woocommerce-checkout-field' ] ) || $field[ 'woocommerce-checkout-field' ] !== 'Yes' ) ) {
                //Check the required field in the case simple upload is used
                $field_name = 'simple_upload_' . wppb_handle_meta_name( $field[ 'meta-name' ] );
                if ( (!isset( $_FILES[ $field_name ] ) || ( isset( $_FILES[ $field_name ] ) && isset( $_FILES[ $field_name ][ 'size' ] ) && $_FILES[ $field_name ][ 'size' ] == 0 ) || !wppb_valid_simple_upload( $field, $_FILES[ $field_name ] ) ) && isset( $request_data[ $field[ 'meta-name' ] ] ) && empty( $request_data[ $field[ 'meta-name' ] ] ) ){/* phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized */ /* no need here for wppb_valid_simple_upload() */
                    return wppb_required_field_error( $field[ 'field-title' ] );
                }
            }
            else{
                //Check the required field in the case the WordPress upload is used
                if ( ( isset( $request_data[wppb_handle_meta_name( $field['meta-name'] )] ) && ( trim( $request_data[wppb_handle_meta_name( $field['meta-name'] )] ) == '' ) ) || !isset( $request_data[wppb_handle_meta_name( $field['meta-name'] )] ) ){
                    return wppb_required_field_error($field["field-title"]);
                }
            }
        }
    }

    return $message;
}
add_filter( 'wppb_check_form_field_upload', 'wppb_check_upload_value', 10, 4 );
